<?php
class BossMain_Model extends Model {
	function __construct() {
		parent::__construct();
	}

	function generateReport() {
		//get the friggin variables
		$since = $_GET['since'];
		$until = $_GET['until'];
		$id_doctor = $_GET['id_doctor'];
		$id_patient = $_GET['id_patient'];
		$id_socialhealth = $_GET['id_socialhealth'];
		$id_speciality = $_GET['id_speciality'];
		$scheduletype =  $_GET['scheduletype'];
		
		$erase_patient = isset($_GET['erase_patient']);
		$erase_doctor = isset($_GET['erase_doctor']);
		$erase_socialhealth = isset($_GET['erase_socialhealth']);
		$erase_speciality = isset($_GET['erase_speciality']);
		
		$select = "SELECT d.name as docName, d.lastname as docLastname, d.dni as docDni, d.dni_type as docDniType,
						  s.date as day, s.status as status, p.name as patName, p.lastname as patLastname, p.dni as patDni, p.dni_type as patDniType,
						  spe.text as speciality, soc.text as socialHealth FROM doctor d, schedule s, patient p, socialhealth soc, speciality spe ";
		if (!$erase_doctor && !$erase_patient && !$erase_socialhealth && !$erase_speciality) {
			$erased = "";
		} else {
			$erased = ""; 
			if ($erase_doctor) {
				$erased .= " and (d.erased = 0)";
			}
			if ($erase_patient) {
				$erased .= " and (p.erased = 0)";
			}
			if ($erase_socialhealth) {
				$erased .= " and (soc.enable = 1)";
			}
			if ($erase_speciality) {
				$erased .= " and (spe.enable = 1)";
			}
		}
		if ($id_doctor !== '') {
			$match_doctor = "and ($id_doctor = s.id_doctor)";
		} else {
			$match_doctor = "";
		}
		if ($id_patient !== '') {
			$match_patient = "and ($id_patient = s.id_patient)";
		} else {
			$match_patient = "";
		}
		if ($id_speciality !== '') {
			$match_speciality = "and ($id_speciality = s.id_speciality)";
		} else {
			$match_speciality = "";
		}
		if ($id_socialhealth !== '') {
			$match_socialhealth = "and ($id_socialhealth = s.id_socialhealth)";
		} else {
			$match_socialhealth = "";
		}
		if ($scheduletype !== '') {
			$match_scheduletype = "and ($scheduletype = s.status)";
		} else {
			$match_scheduletype = "";
		}
		$match_dates = "and (s.date >= $since) and (s.date <= $until)";
		$where = "where (d.id = s.id_doctor) and (p.id = s.id_patient) and (spe.id = s.id_speciality) 
						  and (soc.id = s.id_socialhealth) $match_dates 
						  $match_doctor $match_scheduletype $match_patient $match_speciality $match_socialhealth";
		$query = $select . $where . $erased;
		$result = $this -> db -> select($query);
		$dt = array("aaData" => $result);
		echo json_encode($dt);
	}

}
